package com.lujianfei.babymilkmemory.ui.history

import android.content.Context
import android.net.Uri
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.snapshots.SnapshotStateList
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.lujianfei.babymilkmemory.MyApplication
import com.lujianfei.babymilkmemory.database.AppDatabase
import com.lujianfei.babymilkmemory.database.table.HistoryTable
import com.lujianfei.babymilkmemory.sp.Setting
import com.lujianfei.babymilkmemory.utils.MyLogger
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.File
import java.io.FileOutputStream
import java.util.Timer
import java.util.TimerTask


/**
 * Author: lujianfei
 * Date: 2025/2/13 18:16
 * Description:
 */

class HistoryViewModel:ViewModel() {

    val loading = mutableStateOf(false)

    val list = mutableStateListOf<HistoryModel>()

    val type = mutableIntStateOf(HistoryTable.Type.Pee)

    private var timer:Timer ?= null

    fun load() {
        loading.value = true
        viewModelScope.launch {
            list.clear()
            val respList = withContext(Dispatchers.IO) {
                AppDatabase.instance().historyDao().getAllByType(type = type.intValue)
            }
            if (respList.isEmpty()) {
                loading.value = false
                return@launch
            }
            val listPre = mutableStateListOf<HistoryModel>()
            respList.map { HistoryModel(id = it.id, label = it.getLabel(), create = it.create, uri = mutableStateOf(it.image?:"")) }.let { listPre.addAll(it) }
            listPre.add(0, genNow())
            updateDiffer(listPre)
            list.addAll(listPre)
            loading.value = false

            timer?.cancel()
            timer = Timer()
            timer?.schedule(object : TimerTask() {
                override fun run() {
                    updateNow(list)
                }
            }, 1000, 1000)
        }
    }

    private fun updateNow(list: SnapshotStateList<HistoryModel>) {
        if (list.size > 1) {
            val now = genNow()
            val next = list[1]
            now.differ = now.create - next.create
            list[0] = now
        }
    }

    private fun genNow(): HistoryModel {
        return HistoryModel(id = -1, label = "当前时间", create = (System.currentTimeMillis() / 1000).toInt(), uri = mutableStateOf(""))
    }

    private fun updateDiffer(list: SnapshotStateList<HistoryModel>) {
        for (i in 0 until list.size -1) {
            val current = list[i]
            val next = list[i + 1]
            current.differ =  current.create - next.create
        }
    }

    fun addData() {
        loading.value = true
        viewModelScope.launch {
            withContext(Dispatchers.IO) {
                val twoDaysAgo =  (Setting.INSTANCE.lastTimePee / 1000).toInt()
                AppDatabase.instance().historyDao().insert(HistoryTable(type = type.intValue, create = twoDaysAgo))
            }
            load()
        }
    }

    fun deleteData(model: HistoryModel) {
        loading.value = true
        viewModelScope.launch {
            withContext(Dispatchers.IO) {
                AppDatabase.instance().historyDao().deleteById(model.id)
            }
            load()
        }
    }

    override fun onCleared() {
        super.onCleared()
        timer?.cancel()
    }

    fun setImage(item: HistoryModel, uri: Uri, fromAlbum:Boolean = false) {
        item.uri.value = uri.toString()
        viewModelScope.launch {
            withContext(Dispatchers.IO) {
                if (fromAlbum) {
                    copyUriToInternalStorage(context = MyApplication.INSTANCE, uri = uri, fileName = "${item.id}.jpg")?.let { filePath ->
                        MyLogger.d("HistoryViewModel", "copyUriToInternalStorage filePath:$filePath")
                        AppDatabase.instance().historyDao().update(HistoryTable(id = item.id, type = type.intValue, create = item.create, image = filePath))
                    }
                } else {
                    AppDatabase.instance().historyDao().update(HistoryTable(id = item.id, type = type.intValue, create = item.create, image = item.uri.value) )
                }
            }
        }
    }

    private fun copyUriToInternalStorage(context: Context, uri: Uri?, fileName: String?): String? {
        if (uri == null || fileName.isNullOrEmpty()) {
            return null
        }
        try {
            context.contentResolver.openInputStream(uri).use { inputStream ->
                FileOutputStream(File(context.filesDir, fileName)).use { out ->
                    val buffer = ByteArray(4096)
                    var len: Int
                    while ((inputStream!!.read(buffer).also { len = it }) > 0) {
                        out.write(buffer, 0, len)
                    }
                    return File(context.filesDir, fileName).absolutePath
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
            return null
        }
    }

}